package com.teradata.multithread.smp;

import java.util.concurrent.Semaphore;

/**
 * @author: lyndon
 * @version: 1.0
 * @date: 2019/2/24
 */
public class SemaphoreDemo {
    public static void main(String[] args) {
        final Semaphore semaphore = new Semaphore(4);

        for (int i = 0; i < 20; i++) {
            DoAnything doAnything = new DoAnything(i, semaphore);
            doAnything.start();
        }

    }


    static class DoAnything extends Thread {

        private int num;
        private Semaphore semaphore;

        public DoAnything(int num, Semaphore semaphore) {
            this.num = num;
            this.semaphore = semaphore;
        }

        @Override
        public void run() {
            try {
                semaphore.acquire();
                System.out.println("第" + this.num + "个线程进入运行");
                Thread.sleep(2000);
                semaphore.release();
                System.out.println("第" + this.num + "个线程释放锁");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }





}
